package com.zhiwang.xiaoqu.ui

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.bus.TabChangeEvent
import com.zhiwang.xiaoqu.di.annotation.Injectable
import com.zhiwang.xiaoqu.ktextension.setImmersive
import com.zhiwang.xiaoqu.mvp.model.Store
import com.zhiwang.xiaoqu.mvp.model.response.UpdateCheck
import com.zhiwang.xiaoqu.mvp.presenter.UpdatePresenter
import com.zhiwang.xiaoqu.ui.fragment.MyFragment
import com.zhiwang.xiaoqu.ui.fragment.WebViewFragment
import com.zhiwang.xiaoqu.ui.main.MoneyFragment
import com.zhiwang.xiaoqu.widget.ArcTabBar
import com.zhiwang.xiaoqu.widget.UpdateDialog
import com.zhiwang.xiaoqu.widget.snap.CardAdapterHelper
import com.zhiwang.xiaoqu.widget.snap.CardScaleHelper
import com.zhiwang.xiaoqu.widget.snap.SpeedRecyclerView
import dagger.Lazy
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import javax.inject.Inject
import javax.inject.Named

class MainActivity : BaseActivity(), MoneyFragment.OnFragmentInteractionListener, Injectable {


    val TAG = "MainActivity"
    var colorWhite: Int = 0
    var colorPrimary: Int = 0
    var pendingTabIndex = -1

    @Inject
    lateinit var fragments: Lazy<ArrayList<Fragment>>

    var updateDialog: UpdateDialog? = null

    @Inject
    lateinit var updatePresenter: UpdatePresenter

    @Inject
    lateinit var tabEntities: ArrayList<ArcTabBar.TabParam>


    @Inject
    @field:Named("mainTabTags")
    lateinit var tabFragmentTags: ArrayList<String>

    @Inject
    @field:Named("dummyTags")
    lateinit var tags: ArrayList<String>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.setImmersive(Color.TRANSPARENT, true)
        colorWhite = ContextCompat.getColor(this, R.color.colorWhite1)
        colorPrimary = ContextCompat.getColor(this, R.color.colorPrimary)
        init(savedInstanceState)
        EventBus.getDefault().register(this)
        updatePresenter.checkUpdate(::onUpdate)
    }


    private fun init(savedInstanceState: Bundle?) {

        val fragmentList = arrayListOf<Fragment>()

        if (savedInstanceState != null) {
            val moneyFragment =
                supportFragmentManager.findFragmentByTag(MoneyFragment::class.java.name)
                    ?: MoneyFragment()
            val redPacketFragment = supportFragmentManager.findFragmentByTag(Store.URL_RED_PACKET)
                ?: WebViewFragment.newInstance(Store.URL_RED_PACKET, "")
            val inviteFragment = supportFragmentManager.findFragmentByTag(Store.URL_INVITE)
                ?: WebViewFragment.newInstance(Store.URL_INVITE, "")
            val rankFragment = supportFragmentManager.findFragmentByTag(Store.URL_RANK)
                ?: WebViewFragment.newInstance(
                    Store.URL_RANK,
                    "试玩排行"
                )
            val myFragment = supportFragmentManager.findFragmentByTag(MyFragment::class.java.name)
                ?: MyFragment()

            fragmentList.add(moneyFragment)
            fragmentList.add(redPacketFragment)
            fragmentList.add(inviteFragment)
            fragmentList.add(rankFragment)
            fragmentList.add(myFragment)

        } else fragmentList.addAll(fragments.get())

        arcTabBar.setTabs(
            tabEntities,
            supportFragmentManager,
            R.id.fragment_container,
            fragmentList,
            tabFragmentTags
        )

        if (savedInstanceState != null)
            arcTabBar.select(savedInstanceState.getInt("tabIndex", 0))
        else arcTabBar.select(0)

        arcTabBar.tabSelectedListener = object : ArcTabBar.OnTabSelectedListener {

            override fun onTabSelect(index: Int) {
                when (index) {
                    1 -> {
                        WebViewActivity.load(
                            context = this@MainActivity,
                            url = Store.URL_RED_PACKET,
                            needTitle = false,
                            transparent = true
                        )
                        pendingTabIndex = 0
                    }
                    2 -> {
                        WebViewActivity.load(
                            context = this@MainActivity,
                            url = Store.URL_INVITE,
                            needTitle = false,
                            transparent = true
                        )
                        pendingTabIndex = 0
                    }
                    3 -> {
                        arcTabBar.select(index)
                        window.setImmersive(Color.TRANSPARENT, true)
                    }
                    else -> arcTabBar.select(index)
                }

            }

            override fun onTabUnselect(index: Int) {

            }

            override fun onTabReselect(index: Int) {

            }

        }

    }

    private fun onUpdate(updateCheck: UpdateCheck) {
        if (BuildConfig.VERSION_CODE < updateCheck.version) {
            val notNowBtnVisibility = if (updateCheck.forceUpdate == 1) View.GONE else View.VISIBLE

            updateDialog = UpdateDialog.create(
                this,
                updateCheck.versionName ?: "",
                updateCheck.forceUpdate == 1,
                updateCheck.updateLog ?: "",
                View.OnClickListener { updateNow(updateCheck.url, updateCheck.versionName ?: "") },
                View.OnClickListener { if (updateCheck.forceUpdate == 1) Process.killProcess(Process.myPid()) }
            )

            updateDialog?.dialog?.findViewById<View>(R.id.not_now)?.visibility = notNowBtnVisibility

            updateDialog?.show()

        }
    }

    private fun updateNow(url: String, version: String) {
        updateDialog?.dismiss()
        updateDialog = UpdateDialog.create(this, version)
        updateDialog?.show()


        FileDownloader.getImpl()
            .create(url)
            .setPath(File(filesDir, "xiaoqu$version.apk").absolutePath, false)
            .setListener(object : FileDownloadListener() {
                override fun warn(task: BaseDownloadTask?) {

                }

                override fun completed(task: BaseDownloadTask) {
                    runOnUiThread {
                        updateDialog?.dismiss()
                    }
                    val apkFile = File(task.path)

                    //校验 md5

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        val intent = Intent()
                        intent.`package` = "com.android.installer"
                        intent.setDataAndType(
                            Uri.fromFile(apkFile),
                            "application/vnd.android.package-archive"
                        )
                        startActivity(intent)
                    } else {
                        val uri = FileProvider.getUriForFile(
                            applicationContext,
                            BuildConfig.APPLICATION_ID,
                            apkFile
                        )

                        val intent = Intent()

                        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)

                        intent.setDataAndType(
                            uri,
                            "application/vnd.android.package-archive"
                        )

                        startActivity(intent)

                    }
                }

                override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                }

                override fun error(task: BaseDownloadTask?, e: Throwable?) {
                    if (BuildConfig.DEBUG)
                        Log.i(TAG, "error: ${e?.message}")
                }

                override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
                    if (BuildConfig.DEBUG)
                        Log.i(TAG, "progress: $soFarBytes  $totalBytes")
                    runOnUiThread { updateDialog?.setProgress(Math.round((soFarBytes * 100f) / totalBytes)) }

                }

                override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                }

            })
            .start()


    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("tabIndex", arcTabBar.currSelectedIndex)
    }


    override fun onResume() {
        super.onResume()
        if (pendingTabIndex != -1) {
            arcTabBar.select(pendingTabIndex)
            pendingTabIndex = -1
        }
    }

    override fun onShowDailyRecommendTask() {

        val speedRecyclerView = SpeedRecyclerView(this)

        speedRecyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)


        speedRecyclerView.setItemViewCacheSize(2)
        val dialog = AlertDialog.Builder(this)
            .setView(speedRecyclerView)
            .create()

        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val lp = WindowManager.LayoutParams()
        val attributes = dialog.window?.attributes
        lp.copyFrom(attributes)

        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialog.window?.attributes = lp
        dialog.show()

        val cardScaleHelper = CardScaleHelper()
        cardScaleHelper.currentItemPos = 0
        cardScaleHelper.attachToRecyclerView(speedRecyclerView)
        val recommendTaskAdapter = RecommendTaskAdapter()
        val cardAdapterHelper = CardAdapterHelper()
        cardAdapterHelper.rvWidth = resources.displayMetrics.widthPixels
        recommendTaskAdapter.cardAdapterHelper = cardAdapterHelper
        speedRecyclerView.adapter = recommendTaskAdapter

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTabChangeEvent(event: TabChangeEvent) {
        arcTabBar.select(event.tabIndex)
    }
}
